import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProviderWidget<T extends ChangeNotifier> extends StatefulWidget {
 final T model;
 final Widget child;
 final Function(T) onModelInit;
 final Widget Function(BuildContext context, T value, Widget child) builder;

 const ProviderWidget({Key key,
    @required this.model,
    this.child,
    this.onModelInit,
    @required this.builder})
      : super(key: key);

  @override
  State createState() => _ProviderWidgetState<T>();

  void initModel() {
    if (onModelInit != null) {
      onModelInit(model);
    }
  }
}

class _ProviderWidgetState<T extends ChangeNotifier> extends State<ProviderWidget<T>> {

  @override
  void initState() {
    widget.initModel();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new ChangeNotifierProvider(
      create: (_) => widget.model,
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}
